package com.newtouch.bxzs.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.constant.RabbitMQConstant;
import com.newtouch.bxzs.common.base.em.*;
import com.newtouch.bxzs.common.base.model.Conference;
import com.newtouch.bxzs.common.base.model.PersonalCustomer;
import com.newtouch.bxzs.common.base.model.bo.PushMessageBO;
import com.newtouch.bxzs.common.base.util.*;
import com.newtouch.bxzs.enterprise.mapper.AcceptionCustomerRecordMapper;
import com.newtouch.bxzs.enterprise.mapper.ConferenceMapper;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerMapper;
import com.newtouch.bxzs.enterprise.model.bo.*;
import com.newtouch.bxzs.enterprise.model.vo.*;
import com.newtouch.bxzs.enterprise.service.ConferenceClient;
import com.newtouch.bxzs.enterprise.service.ConferenceService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 营销会议service实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021年1月18日</td>
 * <td>Amour</td>
 * <td>Create</td>
 * </tr>
 * </table>
 * 
 * @author Amour
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class ConferenceServiceImpl implements ConferenceService {

	/** 静态变量：系统日志 */
	private static final Log logger = LogFactory.getLog(ConferenceServiceImpl.class);

	@Autowired
	ConferenceMapper conferenceMapper;
	@Autowired
	PersonalCustomerMapper personalCustomerMapper;
	@Autowired
	ConferenceClient conferenceClient;
	@Autowired
	AmqpTemplate rabbitTemplate;
	@Autowired
	RedisUtils redisUtils;
	@Autowired
	CooperationCompanyUtils cooperationCompanyUtils;
	@Value("${organization.type}")
	private String organType;
	@Autowired
	AcceptionCustomerRecordMapper acceptionCustomerRecordMapper;

	private boolean checkCustomer(String customerName, String customerName1, String customerCertificateType,
			String customerCertificateType1, String customerCertificateNumber, String customerCertificateNumber1) {
		return customerName.equals(customerName1) && customerCertificateType.equals(customerCertificateType1)
				&& customerCertificateNumber.equals(customerCertificateNumber1);
	}

	/**
	 * 校验参数
	 * 
	 * @param conferenceDetail
	 * @param buttonType
	 */
	private void checkParam(ConferenceDetailVO conferenceDetail, String buttonType) {
		if (conferenceDetail == null || StringUtils.isEmpty(conferenceDetail.getMarketingConferenceTheme())
				|| conferenceDetail.getMarketingConferenceDate() == null
				|| conferenceDetail.getMarketingConferenceStartTime() == null
				|| conferenceDetail.getMarketingConferenceEndTime() == null
				|| StringUtils.isEmpty(conferenceDetail.getMarketingConferenceAddress())
				|| StringUtils.isEmpty(conferenceDetail.getMarketingConferenceScale())
				|| StringUtils.isEmpty(buttonType)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
	}

	private void checkParam(String str) {
		if (StringUtils.isEmpty(str)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
	}

	/**
	 * 保存营销会议信息
	 * 
	 * @param userId
	 * @param conferenceModifyVO
	 * @return
	 */
	private String modifyConference(String userId, ConferenceModifyVO conferenceModifyVO) {
		Conference conference = new Conference();
		Date now = new Date();
		// 编辑时只需要修改基本信息
		BeanUtil.copyProperties(conferenceModifyVO.getConferenceDetailVO(), conference);
		conference.setUpdateTime(now);
		conference.setUpdateUserId(userId);
		conference.setPublisherFlag(true);
		if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(conferenceModifyVO.getButtonType())) {
			conference.setMarketingConferenceStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
		} else {
			conference.setMarketingConferenceStatus(PublishStatusEnum.UNPUBLISH_STATUS.getResultCode());
		}
		if (StringUtils.isEmpty(conference.getMarketingConferenceId())) {
			// 新增时需要set其他一些属性
			conference.setCreateTime(now);
			conference.setCreateUserId(userId);
			// 通过按钮类型判断会议状态
			conference.setMarketingConferencePublishOrganizationName(
					UserDetailUtil.getUserDetail().getUserOrganizationName());
			conferenceMapper.insert(conference);
		} else {
			conferenceMapper.updateById(conference);
		}
		// 如果为发布时，推送会议信息至对端
		if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(conferenceModifyVO.getButtonType())) {
			ConferenceDetailBO conferenceDetail = new ConferenceDetailBO();
			BeanUtil.copyProperties(conference, conferenceDetail);
			conferenceDetail.setPublisherFlag(false);
			conferenceDetail.setMarketingConferencePublishOrganizationName(
					UserDetailUtil.getUserDetail().getUserOrganizationName());

			this.pushManyConference(conferenceModifyVO, conferenceDetail);
	/*		if (DistributionTypeEnum.BANK.getCode().equals(organType)) {

			} else {
				this.pushSingleConference(conferenceModifyVO, conferenceDetail);
			}*/
		}
		return conference.getMarketingConferenceId();
	}

	private void pushSingleConference(ConferenceModifyVO conferenceModifyVO, ConferenceDetailBO conferenceDetail) {
		ConferenceAcceptionVO conferenceAcception = new ConferenceAcceptionVO();
		SendHttpRequestUtils<ConferenceAcceptionVO> sendHttpRequestUtils = new SendHttpRequestUtils<>();
		List<String> productCodeList = new ArrayList<>();
		for (ProductVO product : conferenceModifyVO.getProductList()) {
			productCodeList.add(product.getProductCode());
		}
		List<String> cooperationUserJobNumberList = new ArrayList<>();
		for (CooperationUserVO cooperationUser : conferenceModifyVO.getCooperationUserList()) {
			cooperationUserJobNumberList.add(cooperationUser.getCooperationUserJobNumber());
		}
		//添加本端用户与营销会议关联至对端
		List<String> userJobNumberList = new ArrayList<>();
		for (String userJobNumber : conferenceModifyVO.getUserIdList()) {
			userJobNumberList.add(userJobNumber);
		}
		conferenceAcception.setConferenceDetail(conferenceDetail);
		conferenceAcception.setProductCodes(productCodeList);
		conferenceAcception.setCooperationUserJobNumberList(cooperationUserJobNumberList);
		sendHttpRequestUtils.sendHttpRequest(conferenceAcception,
				redisUtils.get(CompanyParameterTypeEnum.CONFERENCE_PUSH.getCode()));
	}

	private void pushManyConference(ConferenceModifyVO conferenceModifyVO, ConferenceDetailBO conferenceDetail) {
		Map<String, ConferenceAcceptionVO> pushMap = new HashMap<>();
		SendHttpRequestUtils<ConferenceAcceptionVO> sendHttpRequestUtils = new SendHttpRequestUtils<>();
		for (ProductVO product : conferenceModifyVO.getProductList()) {
			ConferenceAcceptionVO conferenceAcception = pushMap.get(product.getDataSource());
			List<String> productCodes = new ArrayList<>();
			if (conferenceAcception == null) {
				conferenceAcception = new ConferenceAcceptionVO();
				conferenceAcception.setConferenceDetail(conferenceDetail);
				pushMap.put(product.getDataSource(), conferenceAcception);
			} else {
				productCodes = conferenceAcception.getProductCodes();
			}
			productCodes.add(product.getProductCode());
			conferenceAcception.setProductCodes(productCodes);
		}
		for (CooperationUserVO cooperationUser : conferenceModifyVO.getCooperationUserList()) {
			ConferenceAcceptionVO activityAcceptionVO = pushMap.get(cooperationUser.getDataSource());
			List<String> cooperationUserJobNumberList = new ArrayList<>();
			List<String> userJobNumbers = new ArrayList<>();
			//添加本端用户与营销会议关联至对端
			for (String userJobNumber : conferenceModifyVO.getUserIdList()) {
				userJobNumbers.add(userJobNumber);
			}
			activityAcceptionVO.setUserJobNumberList(userJobNumbers);
			if (activityAcceptionVO == null) {
				activityAcceptionVO = new ConferenceAcceptionVO();
				activityAcceptionVO.setConferenceDetail(conferenceDetail);
				pushMap.put(cooperationUser.getDataSource(), activityAcceptionVO);
			} else if (CollectionUtil.isNotEmpty(activityAcceptionVO.getCooperationUserJobNumberList())) {
				cooperationUserJobNumberList = activityAcceptionVO.getCooperationUserJobNumberList();
			}
			cooperationUserJobNumberList.add(cooperationUser.getCooperationUserJobNumber());
			activityAcceptionVO.setCooperationUserJobNumberList(cooperationUserJobNumberList);
		}

		for (Map.Entry<String, ConferenceAcceptionVO> entry : pushMap.entrySet()) {
			sendHttpRequestUtils.sendHttpRequest(entry.getValue(), cooperationCompanyUtils.getCompanyUrl(entry.getKey(),
					CompanyParameterTypeEnum.CONFERENCE_PUSH.getCode()));
		}

	}

	/**
	 * 保存营销会议客户信息
	 * 
	 * @param conferenceId
	 * @param userId
	 * @param customers
	 */
	// private void modifyCustomer(String conferenceId, String userId,
	// List<CustomerDetailVO> customers) {
	// // 删除关联表数据
	// conferenceMapper.deleteConferenceCustomer(conferenceId);
	// // 批量插入关联表
	// conferenceMapper.insertConferenceCustomer(conferenceId, userId,
	// customers);
	// }

	/**
	 * 保存营销会议产品信息
	 * 
	 * @param conferenceId
	 * @param userId
	 * @param productIdList
	 */
	private void modifyProduct(String conferenceId, String userId, List<String> productIdList) {
		// 先删除关联表中的现有数据然后重新insert
		conferenceMapper.deleteConferenceProduct(conferenceId);
		conferenceMapper.insertConferenceProduct(conferenceId, userId, productIdList);
	}

	/**
	 * 保存合作公司员工信息
	 * 
	 * @param conferenceId
	 * @param userId
	 * @param cooperationUserIdList
	 */
	private void modifyConferenceCooperationUser(String conferenceId, String userId,
			List<String> cooperationUserIdList) {
		// 先删除关联表中的现有数据然后重新insert
		conferenceMapper.deleteConferenceCooperationUser(conferenceId);
		conferenceMapper.insertConferenceCooperationUser(conferenceId, userId, cooperationUserIdList);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#getConferenceList(
	 * com.newtouch.bxzs.enterprise.model.ConferenceVO)
	 */
	@Override
	public IPage<ConferenceBO> getConferenceList(ConferenceVO conferenceVO) {
		if (conferenceVO.getManagerFlag() == null) {
			logger.error("参数是否为管理岗标识为空!");
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		if (conferenceVO.getStoryFlag() == null) {
			logger.error("参数是否查询历史会议标识为空!");
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		Page<ConferenceBO> page = new Page<>(conferenceVO.getCurrentPage(), conferenceVO.getPageSize());
		String userId = UserDetailUtil.getUserDetail().getUserId();
		// 是否查询历史会议
		if (conferenceVO.getStoryFlag()) {
			return conferenceMapper.getConferenceStoryList(page, userId);
		}
		// 是否为管理岗,管理岗查询自己创建的,其他用户查询自己参与的
		if (conferenceVO.getManagerFlag()) {
			Page<Conference> conferencePage = new Page<>(conferenceVO.getCurrentPage(), conferenceVO.getPageSize());
			List<ConferenceBO> bos = new ArrayList<>();
			QueryWrapper<Conference> query = new QueryWrapper<>();
			// 查看自己创建的
			query.eq("CREATE_USER_ID", UserDetailUtil.getUserDetail().getUserId());
			// 营销会议日期
			if (!StringUtils.isEmpty(conferenceVO.getMarketingConferenceDate())) {
				query.eq("MARKETING_CONFERENCE_DATE", DateUtil.beginOfDay(conferenceVO.getMarketingConferenceDate()));
			}
			// 营销会议状态
			if (!StringUtils.isEmpty(conferenceVO.getMarketingConferenceStatus())) {
				query.eq("MARKETING_CONFERENCE_STATUS", conferenceVO.getMarketingConferenceStatus());
			}
			// 营销会议主题
			if (!StringUtils.isEmpty(conferenceVO.getMarketingConferenceTheme())) {
				query.like("MARKETING_CONFERENCE_THEME", conferenceVO.getMarketingConferenceTheme());
			}
			conferencePage = conferenceMapper.selectPage(conferencePage, query);
			if (conferencePage == null || CollectionUtil.isEmpty(conferencePage.getRecords())) {
				return null;
			}
			bos = EntityToBeanUtils.copyBean(conferencePage.getRecords(), ConferenceBO.class);
			for (ConferenceBO bo : bos) {
				bo.setParticipateStatus(false);
			}
			page.setSize(conferencePage.getSize());
			page.setCurrent(conferencePage.getCurrent());
			page.setTotal(conferencePage.getTotal());
			page.setPages(conferencePage.getPages());
			page.setRecords(bos);
			return page;
		} else {
			// 非管理岗需要走多表查询
			return conferenceMapper.getConferenceList(page, userId,
					conferenceVO.getMarketingConferenceDate() == null ? null
							: DateUtil.formatDateTime(conferenceVO.getMarketingConferenceDate()),
					conferenceVO.getMarketingConferenceStatus(), conferenceVO.getMarketingConferenceTheme());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * getConferenceDetail(java.lang.String)
	 */
	@Override
	public ConferenceDetailBO getConferenceDetail(String conferenceId, Boolean managerFlag) {
		this.checkParam(conferenceId);
		return conferenceMapper.getConferenceDetail(managerFlag ? null : UserDetailUtil.getUserDetail().getUserId(),
				conferenceId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * getConferenceCustomerList(java.lang.String, java.lang.String)
	 */
	@Override
	public IPage<ConferenceActivityCustomerBO> getConferenceCustomerList(ConferenceCustomerVO conferenceCustomerVO) {
		if (conferenceCustomerVO.getPublisherFlag() == null || conferenceCustomerVO.getManagerFlag() == null
				|| StringUtils.isEmpty(conferenceCustomerVO.getConferenceId())) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		Page<ConferenceActivityCustomerBO> page = new Page<ConferenceActivityCustomerBO>(
				conferenceCustomerVO.getCurrentPage(), conferenceCustomerVO.getPageSize());
		IPage<ConferenceActivityCustomerBO> result;
		String userId = null;
		if (!conferenceCustomerVO.getManagerFlag()) {
			userId = UserDetailUtil.getUserDetail().getUserId();
		}
		if (conferenceCustomerVO.getPublisherFlag()) {
			// 发布方查询推送记录表
			result = conferenceMapper.getPublisherConferenceCustomerList(page, userId,
					conferenceCustomerVO.getConferenceId(), conferenceCustomerVO.getCustomerName());
		} else {
			// 接收方查询接收记录表
			result = conferenceMapper.getAcceptionConferenceCustomerList(page, userId,
					conferenceCustomerVO.getConferenceId(), conferenceCustomerVO.getCustomerName());
		}
		if (result == null || CollectionUtil.isEmpty(result.getRecords())) {
			return null;
		}
		// 分页控件会使日期格式注解失效，需重新set数据
		List<ConferenceActivityCustomerBO> bos = new ArrayList<>();
		for (ConferenceActivityCustomerBO bo : result.getRecords()) {
			bo.setCustomerCardTypeName(CustomerCardTypeEnum.getNameByCode(bo.getCustomerCertificateType()));
			bos.add(bo);
		}
		result.setRecords(bos);
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * addConferencePersonalCustomer(java.util.List)
	 */
	@Override
	public Integer insertConferencePersonalCustomer(String conferenceId, Boolean personalFlag,
			List<CustomerDetailVO> list) {
		this.checkParam(conferenceId);
		if (CollectionUtil.isEmpty(list)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		// 查询数据库中现有的客户信息，进行去重校验
		List<CustomerInventoryBO> conferenceCustomers = conferenceMapper.getConferenceCustomerList(conferenceId);
		if (!CollectionUtil.isEmpty(conferenceCustomers)) {
			List<CustomerDetailVO> repeatCustomers = new ArrayList<>();
			for (CustomerDetailVO customer : list) {
				for (CustomerInventoryBO conferenceCustomer : conferenceCustomers) {
					boolean repeat = this.checkCustomer(conferenceCustomer.getCustomerName(),
							customer.getCustomerName(), conferenceCustomer.getCustomerCertificateType(),
							String.valueOf(customer.getCustomerCertificateType()),
							conferenceCustomer.getCustomerCertificateNumber(), customer.getCustomerCertificateNumber());
					// 重复时将数据添加至重复集合中
					if (repeat) {
						repeatCustomers.add(customer);
						break;
					}
				}
			}
			// 重复集合不为空时，需要根据标识符进行异常处理
			if (!CollectionUtil.isEmpty(repeatCustomers)) {
				// 添加个人客户时，出现重复则直接抛出异常
				if (personalFlag) {
					StringBuffer sb = new StringBuffer();
					for (CustomerDetailVO customer : repeatCustomers) {
						sb.append("【" + customer.getCustomerName() + "】、");
					}
					throw new BaseException(BaseErrorEnum.DATA_EXISTS.getResultCode(),
							sb.substring(0, sb.length() - 1) + "在本次营销会议客户清单存在，请重新选择");
				}
				list.removeAll(repeatCustomers);
			}
		}
		return CollectionUtil.isEmpty(list) ? 0
				: conferenceMapper.insertConferenceCustomer(conferenceId, UserDetailUtil.getUserDetail().getUserId(),
						list);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * deleteConferencePersonalCustomer(java.lang.String, java.util.List)
	 */
	@Override
	public Integer deleteConferencePersonalCustomer(String conferenceId, String customerId) {
		this.checkParam(conferenceId);
		this.checkParam(customerId);
		return conferenceMapper.deleteConferencePersonalCustomer(conferenceId, customerId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#modifyConference(
	 * com.newtouch.bxzs.enterprise.model.vo.ConferenceModifyVO)
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String modifyConference(ConferenceModifyVO conferenceModifyVO) {
		// 参数校验
		ConferenceDetailVO conferenceDetail = conferenceModifyVO.getConferenceDetailVO();
		this.checkParam(conferenceDetail, conferenceModifyVO.getButtonType());
		// 先保存营销会议信息
		String userId = UserDetailUtil.getUserDetail().getUserId();
		String conferenceId = this.modifyConference(userId, conferenceModifyVO);
		// 保存产品信息
		if (!CollectionUtil.isEmpty(conferenceModifyVO.getProductList())) {
			List<String> productIdList = new ArrayList<>();
			for (ProductVO product : conferenceModifyVO.getProductList()) {
				productIdList.add(product.getProductId());
			}
			this.modifyProduct(conferenceId, userId, productIdList);
		}
		// 保存客户信息,先删除关联表中的数据,再批量insert
		// if
		// (!CollectionUtil.isEmpty(conferenceModifyVO.getConferenceCustomerList()))
		// {
		// this.modifyCustomer(conferenceId, userId,
		// conferenceModifyVO.getConferenceCustomerList());
		// }
		// 更新本端员工与营销会议关联信息
		List<String> deleteUserList = conferenceModifyVO.getUserIdDeleteList();
		List<String> insertUserList = conferenceModifyVO.getUserIdInsertList();
		if (!CollectionUtil.isEmpty(deleteUserList)) {
			// 删除客户关联表中的现有数据
			conferenceMapper.updateConferenceCustomerUser(conferenceId, deleteUserList);
		}
		// 保存营销会议与本端员工关联表信息
		if (!CollectionUtil.isEmpty(insertUserList)) {
			// 先删除用户关联表中的数据
			conferenceMapper.deleteConferenceUser(conferenceId);
			conferenceMapper.insertConferenceUser(conferenceId, userId, insertUserList);
		}
		// 保存合作公司员工信息
		if (!CollectionUtil.isEmpty(conferenceModifyVO.getCooperationUserList())) {
			List<String> cooperationUserList = new ArrayList<>();
			for (CooperationUserVO cooperationUser : conferenceModifyVO.getCooperationUserList()) {
				cooperationUserList.add(cooperationUser.getCooperationUserId());
			}
			this.modifyConferenceCooperationUser(conferenceId, userId, cooperationUserList);
		}
		// 如果为发布时，需要发送通知消息
		if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(conferenceModifyVO.getButtonType())) {
			PushMessageBO message = PushMessageBO.builder().title("营销会议通知")
					.content("您有新的营销会议待参与,主题为:" + conferenceDetail.getMarketingConferenceTheme())
					.noticeJumpId(conferenceDetail.getMarketingConferenceId()).build();
			rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
					RabbitMQUtils.createUserIdRabbitMap(insertUserList, message,
							BusinessMessageEnum.MARKETING_CONFERENCE_MESSAGE_REMINDER.getResultCode()));
		}
		return BaseErrorEnum.SUCCESS.getResultCode();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * getDistributionCustomerList(java.lang.String, java.lang.Boolean)
	 */
	@Override
	public IPage<ConferenceActivityCustomerBO> getDistributionCustomerList(String conferenceId,
			Boolean distributionFlag, Integer currentPage, Integer pageSize) {
		this.checkParam(conferenceId);
		IPage<ConferenceActivityCustomerBO> page = conferenceMapper.getDistributionCustomerList(
				new Page<ConferenceActivityCustomerBO>(currentPage == null ? 1 : currentPage,
						pageSize == null ? 10 : pageSize),
				conferenceId, distributionFlag);
		if (page != null && !CollectionUtil.isEmpty(page.getRecords())) {
			for (ConferenceActivityCustomerBO customer : page.getRecords()) {
				customer.setCustomerCardTypeName(
						CustomerCardTypeEnum.getNameByCode(customer.getCustomerCertificateType()));
			}
		}
		return page;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * modifyDistributionCustomer(java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer modifyDistributionCustomer(DistributionCustomerVO distributionCustomerVO) {
		this.checkParam(distributionCustomerVO.getConferenceId());
		if (CollectionUtil.isEmpty(distributionCustomerVO.getCustomerList())) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		if (StringUtils.isEmpty(distributionCustomerVO.getUserId())){
			//移除分配
			//移除个人客户
			personalCustomerMapper.deleteCustomer(distributionCustomerVO.getCustomerList().get(0).getCustomerId(),true);
			//修改客户id与营销会议关联
			distributionCustomerVO.getCustomerList().get(0).setCustomerId(null);
			return conferenceMapper.updateDistributionCustomer(distributionCustomerVO.getConferenceId(),
					distributionCustomerVO.getUserId(), distributionCustomerVO.getCustomerList());
		}else {
			if (StringUtils.isEmpty(distributionCustomerVO.getUserJobNumber())) {
				throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
			}
			for (int i = 0; i < distributionCustomerVO.getCustomerList().size(); i++) {
				if (StringUtils.isEmpty(distributionCustomerVO.getCustomerList().get(i).getCustomerId())) {
					QueryWrapper<PersonalCustomer> query = new QueryWrapper<>();
					query.eq("CUSTOMER_NAME", distributionCustomerVO.getCustomerList().get(i).getCustomerName());
					query.eq("CUSTOMER_CERTIFICATE_TYPE", distributionCustomerVO.getCustomerList().get(i).getCustomerCertificateType());
					query.eq("CUSTOMER_CERTIFICATE_NUMBER", distributionCustomerVO.getCustomerList().get(i).getCustomerCertificateNumber());
					query.eq("USER_JOB_NUMBER", distributionCustomerVO.getUserJobNumber());
					PersonalCustomer personalCustomer = personalCustomerMapper.selectOne(query);
					if (personalCustomer == null) {
						personalCustomer = new PersonalCustomer();
						// 写入个人客户表
						BeanUtil.copyProperties(distributionCustomerVO.getCustomerList().get(i), personalCustomer);
						// 姓名全拼
						personalCustomer.setCustomerNameFullSpelling(PinYinUtils.toPinyin(personalCustomer.getCustomerName()));
						// 标识
						personalCustomer.setCustomerLabel(CustomerTagEnum.LSSUED.getCode());
						// 所属用户工号
						personalCustomer.setUserJobNumber(distributionCustomerVO.getUserJobNumber());
						personalCustomer.setCreateTime(new Date());
						personalCustomer.setCreateUserId(UserDetailUtil.getUserDetail().getUserId());
						personalCustomerMapper.insert(personalCustomer);
					}
					distributionCustomerVO.getCustomerList().get(i).setCustomerId(personalCustomer.getCustomerId());
				}
			}
		}
		return conferenceMapper.updateDistributionCustomer(distributionCustomerVO.getConferenceId(),
				distributionCustomerVO.getUserId(), distributionCustomerVO.getCustomerList());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#customerAttendance
	 * (java.lang.String, java.lang.String)
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer customerAttendance(String conferenceId, String customerId,String accetptionCustomerRecordId) {
		this.checkParam(conferenceId);
		this.checkParam(customerId);
		int isSuccess = conferenceMapper.customerAttendance(conferenceId, customerId);
		if(isSuccess > 0){
			String unifiedSocialCreditCode = acceptionCustomerRecordMapper.getCooperationCompanyId(accetptionCustomerRecordId);
			String url = cooperationCompanyUtils.getCompanyUrl(unifiedSocialCreditCode,CompanyParameterTypeEnum.ACCEPT_CUSTOMER_ATTENDANCE.getCode());
			Map parMap = new HashMap(2);
			parMap.put("conferenceId",conferenceId);
			parMap.put("customerId",customerId);
			HttpUtil.get(url,parMap);
		}else {
			throw new BaseException("-1","签到失败");
		}
		return isSuccess;
	}

	@Override
	public String acceptCustomerAttendance(String conferenceId, String customerId){
		this.checkParam(conferenceId);
		this.checkParam(customerId);
		int isSuccess = conferenceMapper.customerAttendance(conferenceId, customerId);
		if(isSuccess > 0){
			return "1";
		}
		return "0";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#cancelConference(
	 * java.lang.String)
	 */
	@Override
	public Integer cancelConference(String conferenceId) {
		this.checkParam(conferenceId);
		return conferenceMapper.updateConferenceStatus(conferenceId, PublishStatusEnum.CANCELED_STATUS.getResultCode());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#deleteConference(
	 * java.lang.String)
	 */
	@Override
	public Integer deleteConference(String conferenceId) {
		this.checkParam(conferenceId);
		return conferenceMapper.deleteById(conferenceId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * getConferenceStatistics(java.lang.String)
	 */
	@Override
	public ConferenceActivityStatisticsBO getConferenceStatistics(String conferenceId) {
		this.checkParam(conferenceId);
		ConferenceActivityStatisticsBO result = conferenceMapper.getConferenceStatistics(conferenceId);
		List<String> unifiedSocialCreditCode = conferenceMapper.getUnifiedSocialCreditCodeByConference(conferenceId);
		unifiedSocialCreditCode.stream().forEach(e ->{
			String url = cooperationCompanyUtils.getCompanyUrl(e,CompanyParameterTypeEnum.MARKET_RECOMMENDATION.getCode());
			Map repMap = new HashMap(1);
			repMap.put("relationId",conferenceId);
			String count = HttpUtil.get(url, repMap);
			result.setRecommendationNum(result.getRecommendationNum()+Integer.valueOf(count));
		});
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * acceptionConference(com.newtouch.bxzs.enterprise.model.bo.
	 * ConferenceDetailBO)
	 */
	@Override
	public Integer acceptionConference(ConferenceAcceptionVO conferenceAcception) {
		Conference conference = new Conference();
		BeanUtil.copyProperties(conferenceAcception.getConferenceDetail(), conference);
		conference.setPublisherFlag(false);
		Integer result = conferenceMapper.insertConference(conference);
		if (!CollectionUtil.isEmpty(conferenceAcception.getProductCodes())) {
			// 产品与营销会议关联信息入库
			List<String> productList = conferenceMapper.getProductIdByCode(conferenceAcception.getProductCodes());
			conferenceMapper.insertConferenceProduct(conference.getMarketingConferenceId(), "admin", productList);
		}
		if (!CollectionUtil.isEmpty(conferenceAcception.getCooperationUserJobNumberList())) {
			// 用户与营销会议关联信息入库
			conferenceMapper.insertConferenceUserByJobNumber(conference.getMarketingConferenceId(),
					conferenceAcception.getCooperationUserJobNumberList(),false);
			//对端用户与营销会议关联信息入库
			conferenceMapper.insertConferenceCooperationUserByJobNumber(conference.getMarketingConferenceId(),
					conferenceAcception.getUserJobNumberList(),true);
			// 发送消息通知
			PushMessageBO message = PushMessageBO.builder().title("营销会议通知")
					.content("您有新的营销会议待参与,主题为:" + conference.getMarketingConferenceTheme())
					.noticeJumpId(conference.getMarketingConferenceId()).build();
			rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
					RabbitMQUtils.createUserJobNumberRabbitMap(conferenceAcception.getCooperationUserJobNumberList(),
							message, BusinessMessageEnum.MARKETING_CONFERENCE_MESSAGE_REMINDER.getResultCode()));
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * getConferenceProduct(com.newtouch.bxzs.enterprise.model.vo.
	 * ConferenceProductVO)
	 */
	@Override
	public IPage<ConferenceActivityProductBO> getConferenceProduct(ConferenceProductVO conferenceProductVO) {
		return conferenceMapper.getConferenceProduct(
				new Page<ConferenceActivityProductBO>(conferenceProductVO.getCurrentPage(),
						conferenceProductVO.getPageSize()),
				conferenceProductVO.getConferenceId(), conferenceProductVO.getProductName());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#getConferenceUser(
	 * com.newtouch.bxzs.enterprise.model.vo.ConferenceUserVO)
	 */
	@Override
	public IPage<ConferenceActivityUserBO> getConferenceUser(ConferenceUserVO conferenceUserVO) {
		return conferenceMapper.getConferenceUser(
				new Page<ConferenceActivityUserBO>(conferenceUserVO.getCurrentPage(), conferenceUserVO.getPageSize()),
				conferenceUserVO.getConferenceId(), conferenceUserVO.getSelectCondition());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ConferenceService#
	 * getConferenceCooperationUser(com.newtouch.bxzs.enterprise.model.vo.
	 * ConferenceUserVO)
	 */
	@Override
	public IPage<ConferenceActivityUserBO> getConferenceCooperationUser(ConferenceUserVO conferenceUserVO) {
		return conferenceMapper.getConferenceCooperationUser(
				new Page<ConferenceActivityUserBO>(conferenceUserVO.getCurrentPage(), conferenceUserVO.getPageSize()),
				conferenceUserVO.getConferenceId(), conferenceUserVO.getSelectCondition());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#joinConference(
	 * java.lang.String)
	 */
	@Override
	public Integer joinConference(String userId, String conferenceId) {
		return conferenceMapper.joinConference(userId, conferenceId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#contactCustomer(
	 * java.lang.String)
	 */
	@Override
	public Integer contactCustomer(String conferenceId, CustomerDetailVO customer) {
		return conferenceMapper.contactCustomer(conferenceId, customer);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ConferenceService#pushCustomer(java.
	 * lang.String, com.newtouch.bxzs.enterprise.model.vo.CustomerDetailVO)
	 */
	@Override
	public String pushCustomer(String conferenceId, CustomerDetailVO customer) {
		/*
		 * 若个人客户表中不存在该客户数据,则将客户数据写入个人客户表,否则更新客户与营销会议关联表中的ID
		 */
		// 不存在客户ID时才进行入库操作
		if (StringUtils.isEmpty(customer.getCustomerId())) {
			String userJobNumber = UserDetailUtil.getUserDetail().getUserJobNumber();
			QueryWrapper<PersonalCustomer> query = new QueryWrapper<>();
			query.eq("CUSTOMER_NAME", customer.getCustomerName());
			query.eq("CUSTOMER_CERTIFICATE_TYPE", customer.getCustomerCertificateType());
			query.eq("CUSTOMER_CERTIFICATE_NUMBER", customer.getCustomerCertificateNumber());
			query.eq("USER_JOB_NUMBER", userJobNumber);
			PersonalCustomer personalCustomer = personalCustomerMapper.selectOne(query);
			if (personalCustomer == null) {
				personalCustomer = new PersonalCustomer();
				// 写入个人客户表
				BeanUtil.copyProperties(customer, personalCustomer);
				// 姓名全拼
				personalCustomer.setCustomerNameFullSpelling(PinYinUtils.toPinyin(personalCustomer.getCustomerName()));
				// 标识
				personalCustomer.setCustomerLabel(CustomerTagEnum.LSSUED.getCode());
				// 所属用户工号
				personalCustomer.setUserJobNumber(userJobNumber);
				personalCustomer.setCreateTime(new Date());
				personalCustomer.setCreateUserId(UserDetailUtil.getUserDetail().getUserId());
				personalCustomerMapper.insert(personalCustomer);
			}
			// 更新客户与营销会议关联表
			customer.setCustomerId(personalCustomer.getCustomerId());
			conferenceMapper.updateCustomerId(conferenceId, customer);
			return personalCustomer.getCustomerId();
		}
		return "";
	}

}
